<template>
  <div class="search-page">
    <TopNav :show-back="true"/>

    <main class="main-content">
      <!-- 搜索框 -->
      <div class="search-section">
        <div class="search-box">
          <Search class="search-icon"/>
          <input
              v-model="searchQuery"
              type="text"
              class="search-input"
              placeholder="搜索食谱、食材、菜系..."
              @input="handleSearch"
          />
          <button v-if="searchQuery" @click="clearSearch" class="clear-btn">
            <X :size="20"/>
          </button>
        </div>
      </div>

      <!-- 热门搜索 -->
      <section v-if="!searchQuery && !searchResults.length" class="hot-searches">
        <h3 class="section-title">热门搜索</h3>
        <div class="hot-tags">
          <span
              v-for="tag in hotTags"
              :key="tag"
              class="hot-tag"
              @click="searchByTag(tag)"
          >
            {{ tag }}
          </span>
        </div>
      </section>

      <!-- 搜索结果 -->
      <section v-if="searchQuery" class="search-results">
        <div class="results-header">
          <h3 class="section-title">
            搜索结果 ({{ searchResults.length }})
          </h3>
          <div class="filter-options">
            <select v-model="sortBy" class="filter-select">
              <option value="relevance">相关度</option>
              <option value="rating">评分</option>
              <option value="time">时间</option>
            </select>
          </div>
        </div>

        <div v-if="isSearching" class="loading-state">
          <div class="loading"></div>
          <p>搜索中...</p>
        </div>

        <div v-else-if="searchResults.length === 0" class="empty-state">
          <Search :size="64" class="empty-icon"/>
          <h3>没有找到相关食谱</h3>
          <p>试试其他关键词吧</p>
        </div>

        <div v-else class="results-grid">
          <RecipeCard
              v-for="recipe in filteredResults"
              :key="recipe.id"
              :recipe="recipe"
              @favorite-toggle="toggleFavorite"
          />
        </div>
      </section>

      <!-- 推荐食谱 -->
      <section v-if="!searchQuery" class="recommended-recipes">
        <h3 class="section-title">推荐食谱</h3>
        <div class="recipes-grid">
          <RecipeCard
              v-for="recipe in recommendedRecipes"
              :key="recipe.id"
              :recipe="recipe"
              @favorite-toggle="toggleFavorite"
          />
        </div>
      </section>
    </main>
  </div>
</template>

<script setup lang="ts">
import {computed, onMounted, ref} from 'vue'
import {Search, X} from 'lucide-vue-next'
import TopNav from '@/components/TopNav.vue'
import RecipeCard from '@/components/RecipeCard.vue'

interface Recipe {
  id: string
  title: string
  description: string
  image: string
  cookTime: number
  rating: number
  isFavorite: boolean
  tags: string[]
}

const searchQuery = ref('')
const searchResults = ref<Recipe[]>([])
const isSearching = ref(false)
const sortBy = ref('relevance')

const hotTags = [
  '红烧肉', '宫保鸡丁', '麻婆豆腐', '糖醋排骨',
  '清蒸鲈鱼', '蒜蓉西兰花', '川菜', '粤菜', '家常菜'
]

const mockRecipes: Recipe[] = [
  {
    id: '1',
    title: '红烧肉',
    description: '经典家常菜，肥而不腻，入口即化',
    image: 'https://images.unsplash.com/photo-1565299624946-b28f40a0ca4b?w=400',
    cookTime: 60,
    rating: 4.8,
    isFavorite: false,
    tags: ['红烧肉', '家常菜', '川菜']
  },
  {
    id: '2',
    title: '宫保鸡丁',
    description: '川菜经典，麻辣鲜香，下饭神器',
    image: 'https://images.unsplash.com/photo-1563379091339-03246963d4d0?w=400',
    cookTime: 30,
    rating: 4.6,
    isFavorite: true,
    tags: ['宫保鸡丁', '川菜', '鸡肉']
  },
  {
    id: '3',
    title: '糖醋排骨',
    description: '酸甜可口，老少皆宜的美味',
    image: 'https://images.unsplash.com/photo-1565299507177-b0ac667a2852?w=400',
    cookTime: 45,
    rating: 4.7,
    isFavorite: false,
    tags: ['糖醋排骨', '家常菜', '猪肉']
  },
  {
    id: '4',
    title: '麻婆豆腐',
    description: '四川名菜，麻辣鲜香，嫩滑爽口',
    image: 'https://images.unsplash.com/photo-1563379091339-03246963d4d0?w=400',
    cookTime: 20,
    rating: 4.5,
    isFavorite: true,
    tags: ['麻婆豆腐', '川菜', '豆腐']
  },
  {
    id: '5',
    title: '清蒸鲈鱼',
    description: '清淡鲜美，营养丰富，老少皆宜',
    image: 'https://images.unsplash.com/photo-1565299624946-b28f40a0ca4b?w=400',
    cookTime: 25,
    rating: 4.9,
    isFavorite: false,
    tags: ['清蒸鲈鱼', '粤菜', '鱼类']
  },
  {
    id: '6',
    title: '蒜蓉西兰花',
    description: '清爽健康，简单易做的素菜',
    image: 'https://images.unsplash.com/photo-1563379091339-03246963d4d0?w=400',
    cookTime: 15,
    rating: 4.3,
    isFavorite: false,
    tags: ['蒜蓉西兰花', '素菜', '健康']
  }
]

const recommendedRecipes = ref<Recipe[]>([])

const filteredResults = computed(() => {
  let results = [...searchResults.value]

  switch (sortBy.value) {
    case 'rating':
      results.sort((a, b) => b.rating - a.rating)
      break
    case 'time':
      results.sort((a, b) => a.cookTime - b.cookTime)
      break
    default:
      // 相关度排序（简单实现）
      results.sort((a, b) => {
        const aRelevance = calculateRelevance(a, searchQuery.value)
        const bRelevance = calculateRelevance(b, searchQuery.value)
        return bRelevance - aRelevance
      })
  }

  return results
})

const calculateRelevance = (recipe: Recipe, query: string): number => {
  const queryLower = query.toLowerCase()
  let score = 0

  // 标题匹配
  if (recipe.title.toLowerCase().includes(queryLower)) {
    score += 10
  }

  // 描述匹配
  if (recipe.description.toLowerCase().includes(queryLower)) {
    score += 5
  }

  // 标签匹配
  recipe.tags.forEach(tag => {
    if (tag.toLowerCase().includes(queryLower)) {
      score += 3
    }
  })

  return score
}

const handleSearch = () => {
  if (!searchQuery.value.trim()) {
    searchResults.value = []
    return
  }

  isSearching.value = true

  // 模拟搜索延迟
  setTimeout(() => {
    const query = searchQuery.value.toLowerCase()
    searchResults.value = mockRecipes.filter(recipe =>
        recipe.title.toLowerCase().includes(query) ||
        recipe.description.toLowerCase().includes(query) ||
        recipe.tags.some(tag => tag.toLowerCase().includes(query))
    )
    isSearching.value = false
  }, 500)
}

const searchByTag = (tag: string) => {
  searchQuery.value = tag
  handleSearch()
}

const clearSearch = () => {
  searchQuery.value = ''
  searchResults.value = []
}

const toggleFavorite = (recipeId: string) => {
  const updateFavorites = (recipes: Recipe[]) => {
    const recipe = recipes.find(r => r.id === recipeId)
    if (recipe) {
      recipe.isFavorite = !recipe.isFavorite
    }
  }

  updateFavorites(searchResults.value)
  updateFavorites(recommendedRecipes.value)
}

onMounted(() => {
  recommendedRecipes.value = mockRecipes.slice(0, 4)
})
</script>

<style lang="scss" scoped>
.search-page {
  min-height: 100vh;
  background-color: var(--color-background);
}

.main-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: var(--spacing-md);
}

.search-section {
  margin-bottom: var(--spacing-xl);
}

.search-box {
  position: relative;
  display: flex;
  align-items: center;
  background-color: var(--color-surface);
  border-radius: var(--radius-lg);
  padding: var(--spacing-sm) var(--spacing-md);
  box-shadow: var(--shadow-sm);
}

.search-icon {
  color: var(--color-text-light);
  margin-right: var(--spacing-sm);
}

.search-input {
  flex: 1;
  border: none;
  outline: none;
  font-size: var(--font-size-md);
  background: transparent;

  &::placeholder {
    color: var(--color-text-light);
  }
}

.clear-btn {
  border: none;
  background: none;
  color: var(--color-text-light);
  cursor: pointer;
  padding: var(--spacing-xs);
  border-radius: var(--radius-sm);
  transition: all 0.3s ease;

  &:hover {
    background-color: var(--color-background);
    color: var(--color-text);
  }
}

.hot-searches {
  background-color: var(--color-surface);
  padding: var(--spacing-lg);
  border-radius: var(--radius-lg);
  margin-bottom: var(--spacing-xl);
  box-shadow: var(--shadow-sm);
}

.section-title {
  font-size: var(--font-size-xl);
  font-weight: 600;
  color: var(--color-text);
  margin-bottom: var(--spacing-lg);
}

.hot-tags {
  display: flex;
  flex-wrap: wrap;
  gap: var(--spacing-sm);
}

.hot-tag {
  padding: var(--spacing-xs) var(--spacing-md);
  background-color: var(--color-background);
  color: var(--color-text);
  border-radius: var(--radius-md);
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: var(--font-size-sm);

  &:hover {
    background-color: var(--color-primary);
    color: white;
    transform: translateY(-1px);
  }
}

.search-results {
  margin-bottom: var(--spacing-xl);
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--spacing-lg);
}

.filter-select {
  padding: var(--spacing-xs) var(--spacing-sm);
  border: 2px solid var(--color-border);
  border-radius: var(--radius-md);
  background-color: var(--color-surface);
  color: var(--color-text);
  font-size: var(--font-size-sm);

  &:focus {
    outline: none;
    border-color: var(--color-primary);
  }
}

.loading-state,
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: var(--spacing-xl);
  color: var(--color-text-light);

  .empty-icon {
    margin-bottom: var(--spacing-md);
  }

  h3 {
    font-size: var(--font-size-lg);
    color: var(--color-text);
    margin-bottom: var(--spacing-sm);
  }

  p {
    font-size: var(--font-size-sm);
  }
}

.results-grid,
.recipes-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: var(--spacing-lg);
}

.recommended-recipes {
  background-color: var(--color-surface);
  padding: var(--spacing-lg);
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-sm);
}

@media (max-width: 768px) {
  .results-header {
    flex-direction: column;
    gap: var(--spacing-md);
    align-items: flex-start;
  }

  .results-grid,
  .recipes-grid {
    grid-template-columns: 1fr;
    gap: var(--spacing-md);
  }

  .hot-tags {
    justify-content: center;
  }
}
</style>
